<template>
  <div class="grid_gadget_tempalte"
  style="width:100%;height:100%"
       ref="grid-box"
       :id="'a'+id">
    <Portal to="right-disable"
            v-loading="loading"
            style="width:100%;height:100%"
            :disabled="!queryModelDefaultSetting.showSetting">
      <el-card shadow="never"
               class="aui-card--fill"
               :style="isHasData ? 'width:100%;height: 100%;border:0;overflow: visible;' : 'width:100%;height: 100%;border:0;overflow: hidden;'">
        <div>
          <div class="cardHeader"
               @mouseenter="mouseenter(true)"
               @mouseleave="mouseenter(false)"
               v-if="(widgetName&& widgetName.trim().length>0) || (gadgetSetting.headerDescription && gadgetSetting.headerDescription.trim().length>0)">
            <GadgetTitle :gadgetSetting="gadgetSetting" :widgetName="widgetName"></GadgetTitle>
            <div>

              <MoreMenu :slicer='slicer'
                        :gadgetId='id'
                        :gadgetType='gadgetInfo.com'
                        @updateQuery="query"
                        :widgetName="widgetName"
                        :businessType="gadgetInfo.businessType"
                        :id="gadgetInfo.id"
                        @showQueryModel="showQueryModel" />
            </div>
          </div>
          <div class="control-section"
               style="margin: 10px 10px;"
               :class="warpGridClass">
            <div v-if="gadgetSetting.report"
                 class="content-wrapper"
                  style="width:100%;height:100%;">
              <ejs-grid v-if="isHasData"                        
                        :style="{ height: 'calc(100% - 40px) !important;' }"
                        :dataSource="comDataList"
                        :gridLines='gadgetSetting.report.gridLines'
                        :allowResizing="gadgetSetting.report.allowResizing"
                        :allowFiltering="gadgetSetting.report.allowFiltering"
                        :filterSettings="gadgetSetting.report.filterSettings"
                        :allowGrouping="gadgetSetting.report.allowGrouping"
                        :allowPaging="gadgetSetting.report.allowPaging"
                        :height="gadgetSetting.report.allowGrouping?gadgetHeight - 275 - maxColItem * 36:gadgetHeight -207- maxColItem * 36 + 20"
                        :toolbar="toolbarItem"
                        :allowTextWrap="gadgetSetting.report.allowTextWrap"
                        :textWrapSettings='wrapSettings'
                        :showColumnChooser="gadgetSetting.report.showColumnChooser"
                        :allowReordering="gadgetSetting.report.allowReordering"
                        :allowSorting="gadgetSetting.report.allowSorting"
                        :load="load"
                        :dataBound="dataBound"
                        ref="datagrid"
                        :showColumnMenu='gadgetSetting.report.showColumnMenu'
                        :toolbarClick='toolbarClick'
                        :allowExcelExport='gadgetSetting.report.allowExcelExport'
                        :allowPdfExport='gadgetSetting.report.allowPdfExport'>
                <e-columns v-if="gadgetSetting.report.columns && gadgetSetting.report.columns.length > 0">
                  <e-column v-for="(columnItem, index) in gadgetSetting.report.columns"
                            :key="index"
                            :maxWidth="columnItem.maxWidth?columnItem.maxWidth:'auto'"
                            :fieldsNewFormat='columnItem.fieldsNewFormat'
                            :isNewPage='columnItem.isNewPage'
                            :fieldsList='columnItem.fieldsList'
                            :fieldsFormat='columnItem.fieldsFormat'
                            :showbymonday='columnItem.showbymonday'
                            :autoFit="columnItem.autoFit"
                            :field='columnItem.field'
                            :headerText='columnItem.headerText'
                            :customAttributes="{class: 'e-attr'}"
                            :sortComparer='columnItem.type === "number"?sortComparer:""'
                            :textAlign="columnItem.textAlign"
                            :disableHtmlEncode="columnItem.disableHtmlEncode"
                            :type="columnItem.type"
                            :headerTextTooltip=columnItem.headerTextTooltip
                            :filter='columnItem.filter'
                            :template='formatForGrid[columnItem.templateName]'
                            :visible='columnItem.visible'>
                  </e-column>
                </e-columns>
            </ejs-grid>
            <Pagination
                  v-if="isHasData && gadgetSetting.report.allowPaging"
                  @query="query"
                  v-model="pageConfig"></Pagination>
              <div v-else
                   class="gadget-no-data">
                <el-image @click="query()"
                          :src="noDataImageUrl"
                          fit="fill"></el-image>
              </div>
            </div>
          </div>
        </div>
      </el-card>
      <Lastupdatetime v-if="currentTime"
                      :currentTime="currentTime"
                      :linkedDatasetList="linkedDatasetList"
                      @updateQuery="query()"></Lastupdatetime>
    </Portal>
    <model :showSetting="queryModelDefaultSetting.showSetting"
           @queryModelClosed="queryModelClosed"
           @queryModelPreview="queryModelPreview"
           :selectFields="selectFields"
           :dataInfo="queryModelDefaultSetting.dataInfo"
           :updateGadget="upgradeGadgetSetting"
           @saveGadgetSetting='saveGadgetSetting' />
    <DrillThrough :gadgetId='id'
                  :pageId='pageId'
                  :slicer="slicer"
                  :queryId="queryId"
                  ref="drill-through"
                  :widgetName='widgetName' />
  </div>
</template>

<script>
import Vue from 'vue'
import mixinGadgetViewModule from '@/mixins/gadget-view-module'
import Lastupdatetime from '@/components/last-update-time/index.vue'
import http from '@/utils/request'
//import { Page, Group, Sort, Reorder, ColumnChooser, Toolbar, Filter, DetailRow, Resize, Freeze, ColumnMenu, PdfExport, ExcelExport, GridPlugin } from '@syncfusion/ej2-vue-grids'
import { defaultGadgetSettingList } from '@/utils/data-json'
import mixinFormatViewModule from '@/mixins/format-gadget-view-module'
import { randomString } from '@/utils'
//Vue.use(GridPlugin)
export default {
  mixins: [mixinGadgetViewModule, mixinFormatViewModule],
  components: { Lastupdatetime },
  data () {
    return {

      currentTime: null,
      floatNum: 0,
      maxColItem: 0,
      gadgetSetting: {},
      AggColumn: [],
      mixinViewModuleOptions: {
        pageId: this.pageId
      },
      isGridInit: false,
      dataList: [],
      loading: false,
      heightoffset: 60,
      queryModelDefaultSetting: {
        showSetting: false,
        dataInfo: {
          businessId: this.pageId,
          gadgetId: this.id,
          gadgetType: 'apigridgadget',
          gadgetSetting: this._.find(defaultGadgetSettingList, { gadgetType: 'apigridgadget' }).gadgetSetting
        }
      },
      toolbarItem: [], // 'ExcelExport'
      wrapSettings: { wrapMode: 'Both' },
      queryId: '',
      queryDrillthrough: {},
      queryDrillthroughList: [],
      selectFields: [],
      widgetName: '',
      linkedDatasetList: [],
      recordNum: 0,
      randomStr: randomString(),
      fxFields: [],
      formatDataList: [],
      isShowCursor: false,
      queryFields: []
    }
  },
  // provide: {
  //   grid: [Group, Page, Sort, Reorder, Resize, ColumnChooser, Toolbar, Freeze, Filter, DetailRow, ColumnMenu, PdfExport, ExcelExport]
  // },
  beforeCreate () {
    this.$options.components.model = () => import('@/components/gadget/query-model/query-model')
  },
  created () {
    // this.query()
    Vue['_this'] = this
    this.subscribeMessage('runReport', this.query)
    this.$store.state.isWidget = false
  },
  computed: {
    comDataList () {
      var _self = this
      var retdata = _self.dataList
      return retdata
    },
    warpGridClass () {
      return this.randomStr
    }
  },
  watch: {
    editMode (val) {
      if (val) {
        // console.log('sss', this.grid.ej2Instances.getPersistData())
      }
    }
  },
  methods: {
    sortComparer: function (reference, comparer) {
      if (reference === 0 && this.isNull(comparer)) {
        return 1
      }
      if (Number(reference) < Number(comparer)) {
        return -1
      }
      if (Number(reference) > Number(comparer)) {
        return 1
      }
      return 0
    },
    isNull (value) {
      if (!value && typeof value !== 'undefined' && value !== 0) {
        return true
      } else {
        return false
      }
    },
    dataBound (args) {
      if (!this.gadgetSetting.report.allowPaging) {
        let recordNum = document.querySelector(`.grid_gadget_tempalte .${this.randomStr} .e-content`).offsetHeight
        if (!this.recordNum) this.recordNum = recordNum
        document.querySelector(`.grid_gadget_tempalte .${this.randomStr} .e-content`).style.height = (this.recordNum + 60) + 'px'
      }
      this.$emit('gadgetSettingroupSettingsColumns', this.grid.ej2Instances.groupSettings.columns)
      if (!this.isGridInit) {
        this.isGridInit = true
        this.applyGadgetSetting()
      }
    },
    load (item) {
      this.grid = this.$refs.datagrid
      this.gadgetHeight = this.gadgetInfo.h * 20 - 15
    },
    applyGadgetSetting () {
      let columnsList = []
      let isAutofit = false
      // process link column
      for (let index = 0; index < this.gadgetSetting.report.columns.length; index++) {
        const element = this.gadgetSetting.report.columns[index]
        // add template and drillThrough
        columnsList.push(element.field)
        if (this.gadgetSetting.report.columns[index].type === 'datetime') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
        if (this.gadgetSetting.report.columns[index].type === 'date') {
          this.gadgetSetting.report.columns[index].type = 'text'
        }
      }
      if (isAutofit) {
        columnsList = Object.keys(this.dataList[0])
        this.grid.ej2Instances.autoFitColumns(columnsList)
      }
      this.grid.ej2Instances.setProperties(this.gadgetSetting.report)
      this.$forceUpdate()
    },
    queryModelClosed () {
      this.queryModelDefaultSetting.showSetting = false
      this.query(true)
    },
    queryModelPreview () {
      this.query(true)
    },
    showQueryModel () {
      this.queryModelDefaultSetting.showSetting = true
    },
    resized (i, newH, newW, newHPx, newWPx) {
      this.gadgetHeight = newH * 20 - this.heightoffset - 15
      this.gadgetWidth = newWPx
    },
    toolbarClick (args) {
      var excelExportProperties = {}
      switch (args.item.text) {
        case 'PDF Export':
          excelExportProperties = {
            dataSource: this.formatDataList
          }
          this.$refs.datagrid.pdfExport(excelExportProperties)
          break
        case 'Excel Export':
          excelExportProperties = {
            dataSource: this.formatDataList
          }
          this.$refs.datagrid.excelExport(excelExportProperties)
          break
        case 'CSV Export':
          excelExportProperties = {
            dataSource: this.formatDataList
          }
          this.$refs.datagrid.csvExport(excelExportProperties)
          break
      }
    },
    query () {
      if (this.loading) {
        return false
      }
      // this.dataList = []
      this._.merge(this.gadgetSetting, this.queryModelDefaultSetting.dataInfo.gadgetSetting)
      try {
        this.gadgetSetting.report.columns = []
      } catch (error) { }
      this.isHasData = false
      this.loading = true
      let _self = this
      let obj = JSON.parse(JSON.stringify(this.slicer))

      for (let key in obj) {
        if (key === 'id') {
          delete obj.id
        }
      }
      let param = {
        ...obj,
        slicer: { ...this.slicer },
        pageId: this.pageId,
        gadgetId: this.id,
        filter: this.getFilterStr(),
        type: this.filterType
      }
      if (!param.pageId) {
        param.type = 'widget'
      }
      _self.queryDrillthrough = {}
      _self.queryDrillthroughList = []
      _self.selectFields = []
      _self.$interface.reports.getReportDataInfo(param)
        .then(({ data: res }) => {
          this.currentTime = new Date()
          _self.heightoffset = 5
          _self.gadgetHeight = (_self.gadgetInfo.h * 20) - _self.heightoffset - 15
          if (res.config) {
            _self.gadgetSetting = Object.assign({}, _self._.merge(_self.gadgetSetting, res.config))
          }
          if (res.name) {
            _self.widgetName = res.name
          } else {
            _self.widgetName = _self.gadgetSetting.headerTitle
          }
          _self.selectFields = res.selectFields
          if (this.gadgetSetting.apiURL) {
            _self.requestData(this.gadgetSetting.method, this.gadgetSetting.apiURL, this.gadgetSetting.requestData)
          }

          _self.loading = false
          _self.queryFields = res.selectFields
        })
        .catch(() => {
          _self.loading = false
        })
    },
    requestData (method, apiURL, requestData) {
      let _self = this  
      const params = {
        ...requestData
      }
      if (_self.gadgetSetting.report.allowPaging) {
        if (_self.$route.path !== '/publicReportPdf') {
          params[requestData.pageConfig.page] = _self.pageConfig.current;
          params[requestData.pageConfig.pageSize]  = _self.pageConfig.pageSize;
        }
      }
      if(params.pageConfig) delete params.pageConfig
      if (!apiURL.startsWith('http')) apiURL = http.options.baseURL + apiURL
      _self.$interface.customRequest(method, apiURL, params).then(({ data: res }) => {
        if (res.code !== 0) {
          return _self.$message.error(res.msg)
        }        
        _self.verifyHasData(res)
        try {
              if (res.data.records) {
                _self.pageConfig.total = res.data.total;
                _self.pageConfig.pages = res.data.pages;
                _self.dataList = res.data.records
              } else {
                _self.dataList = res.data
              }
        } catch (error) {}
        //this.dataList = res.data
        _self.isGridInit = false
      }).finally(() => {
        _self.loading = false
        _self.updateGadgetLoadingStatus(!this.loading)
      })
    },
    destroyed () {
      delete Vue['_this']
    },
    remove () {
      this.close()
      if (this.drop.parentNode) {
        this.drop.parentNode.removeChild(this.drop)
      }
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .e-attr {
  white-space: pre !important;
}
.grid_gadget_tempalte ::v-deep .showToobar .e-grid .e-toolbar {
  display: none;
}
.grid_gadget_tempalte ::v-deep .e-grid .e-summarycell {
  font-size: 13px;
  background-color: #f6f6f6;
  border-color: #e0e0e0;
  color: rgba(0, 0, 0, 0.54);
  font-weight: normal;
}
.el-card ::v-deep .el-card__body {
  padding: 0px !important;
}

.el-card ::v-deep .el-divider--horizontal {
  margin: 3px 0 !important;
}

.threepoints {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.cardHeader {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 6px 20px;
  border-bottom: 1px solid #eee;
  position: relative;
}

.cardIcon {
  font-size: 16px;
  font-weight: 600;
  margin-left: 10px;
  position: relative;
  top: -2px;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  cursor: pointer;
}

.header {
  display: flex;
  height: 32px;
  justify-content: space-around;
  text-align: center;
  background: no-repeat;
  background-size: cover;
}

.e-grid ::v-deep .e-filter-popup {
  max-height: 300px !important;
  overflow-y: auto;
}

.e-grid ::v-deep .e-checkboxlist {
  height: auto !important;
  overflow-y: visible !important;
}
::v-deep .e-gridpager {
  display: none;
}
</style>
<style lang="scss">
.grid_gadget_tempalte {
  .e-popup.e-popup-open.e-dialog {
    display: inline-flex !important;
  }
}
</style>
